import java.util.ArrayList;
import java.util.List;

class Solution {
    List<Integer> result;
    int path = 0;
    int m = 0;
    int n = 0;
    boolean[][] check;
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public int getMaximumGold(int[][] grid) {
        result = new ArrayList<>();
        m = grid.length;
        n = grid[0].length;
        check = new boolean[m][n];
        int max = 0;

        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] != 0){
                    dfs(grid, i, j);
                }
            }
        }
        for(int i = 0; i < result.size(); i++){
            max = Math.max(max, result.get(i));
        }
        return max;
    }
    public void dfs(int[][] grid, int i, int j){
        path += grid[i][j];
        check[i][j] = true;
        for(int k = 0; k < 4; k++){
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && check[x][y] == false && grid[x][y] != 0){
                dfs(grid, x, y);
            }
        }
        result.add(path);
        path -= grid[i][j];
        check[i][j] = false;
    }
}